<?php
namespace app\api\controller;

use app\common\controller\Common;
use think\Db;

class Version extends Base
{
    // public function _initialize()
    // {
    //     //parent::_initialize();
    // }
    /**
     * 获取版本列表
     * 参数
     * limit    条数
     * page     分页页数
     */
    public function getList($limit = '10', $page = '1')
    {
        //检测是否有分页
        $limit = input('param.limit') ? input('param.limit') : $limit;
        $page = input('param.page') ? input('param.page') : $page;
        $model = Model('Version');
        try{
            $results = $model->getDate([], $limit, $page);
            $total = $model->where([])->count();
        }catch(\Exception $e)
        {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
        $data = [
            'list' => $results,
            'total' => $total,
            'total_page' => ceil($total/$limit)
        ];
        return resultArray(['data' => $data]);
    }

    /**
     *  获取最近的版本记录数据
     */
    public function getLatestDate()
    {
        try{
            $model = Model('Version');
            //获取一条最新的数据
            $box = $model->where('device_type', '1')->order('version_id desc')->limit(1)->find();
            if($box){
                $result['list'][] = $box;
            }
            $pen = $model->where('device_type', '2')->order('version_id desc')->limit(1)->find();
            if($pen){
                $result['list'][] = $pen;
            }
            if (empty($result['list'])) {
                //return resultArray(['error' => '查找数据集为空']);
                return resultArray(['data' => []]);
            }
            $type_arr = [1 => '终端', 2 => '录音笔'];
            $status_detail = ['禁用', '启用'];
            $force_arr = ['否', '是'];
            foreach($result['list'] as $list){
                $list['type_detail'] = $type_arr[$list['device_type']];
                $list['is_force_detail'] = $force_arr[$list['is_force']];
                $list['detail'] =  $status_detail[$list['status']];
            }
            return resultArray(['data' => $result]);
        }catch(\Exception $e){
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
    }

    /**
     * 上传版本包
     * 参数
     * file 上传文件
     * update_info  更新提示详情
     * version 上传版本
     */
    public function uploadVersionPackage()
    {
        //修改跨域
        header("Access-Control-Allow-Origin: *");
        if (!request()->isPost()) {
            return resultArray(['error' => '上传类型错误']);
        }
        try {
            //从配置文件获取上传路径
            $path = config('huisheng.package_upload_path');
            $file = request()->file('file');
            if (empty($file)) {
                return resultArray(['error' => '升级包上传失败']);
            }
            //获取文件名
            $filename = $file->getInfo()['name'];
            //格式化文件名字
            $formatname = trim(date('YmdHis', time()) . rand(1000, 9999) . "." . substr(strrchr($filename, '.'), 1));
            Db::startTrans();
            //插入数据库
            $data = [
                'update_info' => input('post.update_info') ? input('post.update_info') : '',
                'version' => input('post.version'),
                'create_time' => time(),
                'update_url' => $formatname,
                'code' => input('post.code') ? input('post.code') : 0,
                'device_type' => input('post.type')?:1,
            ];
            $model = Model('Version');
            $validate = $model->createDates($data);
            if(!$validate)
            {
                return resultArray(['error' => $model->getError()]);
            }
            // 把包上传到指定的文件夹,判断后缀为apk，上传最大20mb
            $info = $file->validate(['size' => 20971520, 'ext'=>'apk'])->move($path, $formatname);
            if(!$info)
            {
                return resultArray(['error' => '上传文件超过预定大小']);
            }
            Db::commit();
            return resultArray(['data' => '']);
        } catch (\Exception $e) {
            //回滚删文件
            Db::rollback();
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
    }

    /**
     * 删除版本包
     * 参数
     * version_id   主键id
     */
    public function delPackage()
    {
        if (request()->isPost()) {
            $id = input('param.version_id');
            $model = Model('Version');
            Db::startTrans();
            try {
                //查询出指定id的数据是否存在
                $result = $model->getDate(['version_id' => $id]);
                if (!$result) {
                    return resultArray(['error' => '删除失败，数据不存在']);
                }
                $path = $result['update_url'];
                if (is_file($path)) {
                    unlink($path);
                }
                //删除指定id的数据
                $result = $model->delDataById($id);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                //return resultArray(['error' => $e->getMessage()]);
                return resultArray(['error' => '请求失败']);
            }
            return resultArray(['data' => '']);
        }
    }

    /**
     * 强制更新
     */
    public function forceUpdate()
    {
        try{
            $eids = input('param.eids');
            if(!$eids)
            {
                $version_model = Model('Version');
                //获取一条最新的数据
                $result = $version_model->order('version_id desc')->limit(1)->find();
                if (empty($result)) {
                    return resultArray(['error' => '未找到最近的安装包,请上传最新安装包']);
                }
                $result->is_force = 1;
                $result->save();
                return resultArray(['data' => '']);
            }else{
                $eids = explode(',', $eids);
                $version_model = Model('Version');
                $result = $version_model->equsToVersion($eids);
                if (!$result) {
                    return resultArray(['error' => $version_model->getError()]);
                }
                return resultArray(['data' => '']);
            }
        }catch(\Exception $e){
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
    }


    public function editVersion(){
        $param = input('param.');
        $result = Model('Version')->updateDataById($param, $param['version_id']);
        if($result){
            return resultArray(['data' => '']);
        }
        return resultArray(['error' => $result->getError]);
    }
}
